package com.jinxin.platform.cdperprotypay.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jinxin.platform.cdperprotypay.mapper.ChargeDetailMapper;
import com.jinxin.platform.cdperprotypay.mapper.ChargeItemsMapper;
import com.jinxin.platform.cdperprotypay.mapper.ChargeRoomDetailMapper;
import com.jinxin.platform.cdperprotypay.mapper.ChargeStandardMapper;
import com.jinxin.platform.cdperprotypay.pojo.bo.PageBo;
import com.jinxin.platform.cdperprotypay.pojo.bo.SysHouse;
import com.jinxin.platform.cdperprotypay.pojo.domain.*;
import com.jinxin.platform.cdperprotypay.pojo.form.ChargeRoomDetailForm;
import com.jinxin.platform.cdperprotypay.pojo.form.RoomDetailForm;
import com.jinxin.platform.cdperprotypay.pojo.vo.ChargeStandardVO;
import com.jinxin.platform.cdperprotypay.pojo.vo.RoomDetailVo;
import com.jinxin.platform.cdperprotypay.service.ChargeRoomDetailService;
import com.jinxin.platform.cdperprotypay.support.ModularSupport;
import org.springframework.stereotype.Service;
import com.jinxin.platform.base.common.pojo.JsonResult;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 单一收费项目缴费详情表(ChargeRoomDetail)表服务实现类
 *
 * @author zhangpeng
 * @since 2020-06-28 17:31:04
 */
@Service("chargeRoomDetailService")
public class ChargeRoomDetailServiceImpl implements ChargeRoomDetailService {
    @Resource
    private ChargeRoomDetailMapper chargeRoomDetailMapper;
    @Resource
    private ModularSupport modularSupport;
    @Resource
    private ChargeStandardMapper chargeStandardMapper;
    @Resource
    private ChargeDetailMapper chargeDetailMapper;
    @Resource
    private ChargeItemsMapper chargeItemsMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public JsonResult queryById(String id) {
        ChargeRoomDetail chargeRoomDetail = this.chargeRoomDetailMapper.queryById(id);
        return JsonResult.ok(chargeRoomDetail);
    }

    /**
     * 通过实体作为筛选条件查询
     *
     * @param chargeRoomDetail 实例对象
     * @return 对象列表
     */
    @Override
    public JsonResult queryAll(ChargeRoomDetail chargeRoomDetail) {
        List<ChargeRoomDetail> chargeRoomDetailList = this.chargeRoomDetailMapper.queryAll(chargeRoomDetail);
        return JsonResult.ok(chargeRoomDetailList);
    }

    /**
     * 新增数据
     *
     * @param chargeRoomDetailForm 实例对象
     * @return 实例对象
     */
    @Override
    public JsonResult insert(ChargeRoomDetailForm chargeRoomDetailForm) {
        String[] split = chargeRoomDetailForm.getRoomId().split(";");
        if (split.length == 0 || split[0].equals("")) {
            return JsonResult.error("请选择房间！");
        }
        if (chargeRoomDetailForm.getAfterStandard() != null && chargeRoomDetailForm.getAfterStandard().equals("1")) { //清除之前的收费标准
            for (String s : split) {
                chargeRoomDetailMapper.delete(chargeRoomDetailForm.getItemsId(), s);
            }
        }
        ChargeItems chargeItems = chargeItemsMapper.queryById(chargeRoomDetailForm.getItemsId());
        for (String s : split) {
            ChargeRoomDetail chargeRoomDetail = new ChargeRoomDetail();
            chargeRoomDetail.setStandardId(chargeRoomDetailForm.getStandardId());
            chargeRoomDetail.setChargeStime(chargeRoomDetailForm.getStartTime());
            chargeRoomDetail.setItemsId(chargeRoomDetailForm.getItemsId());
            chargeRoomDetail.setRemark(chargeRoomDetailForm.getRemark());
            chargeRoomDetail.setMoneys(chargeRoomDetailForm.getMoneys());
            if (chargeRoomDetailForm.getUserId() != null) {
                chargeRoomDetail.setUserId(chargeRoomDetailForm.getUserId());
            }
            chargeRoomDetail.setRoomId(s);
            if (chargeRoomDetailForm.getEndTime() != null) {
                chargeRoomDetail.setChargeEtime(chargeRoomDetailForm.getEndTime());
            }
            chargeRoomDetailMapper.insert(chargeRoomDetail);
            HashMap<Object, Object> map = new HashMap<>();
            map.put("roomId", chargeRoomDetail.getRoomId());
            SysHouse sysHouse = modularSupport.getRoomById(map);

            if (chargeRoomDetailForm.getEndTime() != null) {
                List<String> monthBetween = new ArrayList<>();

                if (chargeItems.getItemsCycle().equals("1")) { //表示当期收当期的费用
                    Calendar min = Calendar.getInstance();
                    Calendar max = Calendar.getInstance();

                    min.setTime(chargeRoomDetailForm.getStartTime());
                    max.setTime(chargeRoomDetailForm.getEndTime());

                    monthBetween = getMonthBetween(min, max);
                }

                if (chargeItems.getItemsCycle().equals("2")) { //表示当期收上期的费用，生成上一个月的账单
                    Calendar min = Calendar.getInstance();
                    Calendar max = Calendar.getInstance();

                    min.setTime(chargeRoomDetailForm.getStartTime());
                    min.set(Calendar.MONTH, min.get(Calendar.MONTH) - 1);

                    max.setTime(chargeRoomDetailForm.getEndTime());
                    max.set(Calendar.MONTH, max.get(Calendar.MONTH) - 1);

                    monthBetween = getMonthBetween(min, max);

                }

                if (chargeItems.getItemsCycle().equals("3")) { //表示当期收下期的费用，生成下一个月的账单
                    Calendar min = Calendar.getInstance();
                    Calendar max = Calendar.getInstance();

                    min.setTime(chargeRoomDetailForm.getStartTime());
                    min.set(Calendar.MONTH, min.get(Calendar.MONTH) + 1);

                    max.setTime(chargeRoomDetailForm.getEndTime());
                    max.set(Calendar.MONTH, max.get(Calendar.MONTH) + 1);

                    monthBetween = getMonthBetween(min, max);


                }

//                List<String> monthBetween = getMonthBetween(chargeRoomDetailForm.getStartTime(), chargeRoomDetailForm.getEndTime());
                for (String str : monthBetween) {
                    String dataTime = getFirstAndLastDayOfMonth(str);
                    ChargeDetail chargeDetail = new ChargeDetail();
                    chargeDetail.setRoomId(chargeRoomDetail.getRoomId());
                    chargeDetail.setDataTime(dataTime);

                    if (!chargeItems.getItemsType().equals("1")) {
                        chargeDetail.setBuildId(sysHouse.getBuildId());
                        chargeDetail.setUnitId(sysHouse.getUnitId());
                        chargeDetail.setVillageId(sysHouse.getVillageId());
                        chargeDetail.setIsCharge("未缴费");
                        chargeDetail.setChargeRdId(chargeRoomDetail.getId());
                        chargeDetailMapper.insert(chargeDetail);
                        map.put("dataTime", chargeDetail.getDataTime());
                        map.put("itemsName", chargeItems.getItemsName());
                        map.put("roomId", s);
                        modularSupport.event(map);
                    } else { //周期性缴费判断重复
                        boolean status = true;
                        List<ChargeDetail> chargeDetails = chargeDetailMapper.queryAll(chargeDetail);
                        for (ChargeDetail chargeDetail1 : chargeDetails) {
                            ChargeRoomDetail queryById = chargeRoomDetailMapper.queryById(chargeDetail1.getChargeRdId());
                            if (queryById.getItemsId().equals(chargeItems.getId())) {
                                status = false;
                                break;
                            }
                        }
                        if (status) {  //根据数据时间-房间id判断是否有重复数据
                            chargeDetail.setBuildId(sysHouse.getBuildId());
                            chargeDetail.setUnitId(sysHouse.getUnitId());
                            chargeDetail.setVillageId(sysHouse.getVillageId());
                            chargeDetail.setIsCharge("未缴费");
                            chargeDetail.setChargeRdId(chargeRoomDetail.getId());
                            chargeDetailMapper.insert(chargeDetail);
                            map.put("dataTime", chargeDetail.getDataTime());
                            map.put("itemsName", chargeItems.getItemsName());
                            map.put("roomId", s);
                            modularSupport.event(map);
                        }
                    }

                }
            } else {
                Date date = new Date(); //获取当前的系统时间。
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); //使用了默认的格式创建了一个日期格式化对象。
                String time = dateFormat.format(date); //可以把日期转换转指定格式的字符串

                if (chargeItems.getItemsCycle().equals("3")) { //表示当期收下期的费用，生成下一个月的账单
                    Calendar instance = Calendar.getInstance();
                    instance.add(instance.MONTH, 1);
                    time = dateFormat.format(instance);
                }

                String dataTime = getFirstAndLastDayOfMonth(time);
                ChargeDetail chargeDetail = new ChargeDetail();
                chargeDetail.setRoomId(chargeRoomDetail.getRoomId());
                chargeDetail.setDataTime(dataTime);
                if (!chargeItems.getItemsType().equals("1")) {
                    chargeDetail.setBuildId(sysHouse.getBuildId());
                    chargeDetail.setUnitId(sysHouse.getUnitId());
                    chargeDetail.setVillageId(sysHouse.getVillageId());
                    chargeDetail.setIsCharge("未缴费");
                    chargeDetail.setChargeRdId(chargeRoomDetail.getId());
                    chargeDetailMapper.insert(chargeDetail);
                    map.put("dataTime", chargeDetail.getDataTime());
                    map.put("itemsName", chargeItems.getItemsName());
                    map.put("roomId", s);
                    modularSupport.event(map);
                } else { //周期性缴费判断重复
                    boolean status = true;
                    List<ChargeDetail> chargeDetails = chargeDetailMapper.queryAll(chargeDetail);
                    for (ChargeDetail chargeDetail1 : chargeDetails) {
                        ChargeRoomDetail queryById = chargeRoomDetailMapper.queryById(chargeDetail1.getChargeRdId());
                        if (queryById.getItemsId().equals(chargeItems.getId())) {
                            status = false;
                            break;
                        }
                    }
                    if (status) {  //根据数据时间-房间id判断是否有重复数据
                        chargeDetail.setBuildId(sysHouse.getBuildId());
                        chargeDetail.setUnitId(sysHouse.getUnitId());
                        chargeDetail.setVillageId(sysHouse.getVillageId());
                        chargeDetail.setIsCharge("未缴费");
                        chargeDetail.setChargeRdId(chargeRoomDetail.getId());
                        chargeDetailMapper.insert(chargeDetail);
                        map.put("dataTime", chargeDetail.getDataTime());
                        map.put("itemsName", chargeItems.getItemsName());
                        map.put("roomId", s);
                        modularSupport.event(map);
                    }
                }

            }

        }

        return JsonResult.ok("新增成功", null);
    }

    /**
     * 修改数据
     *
     * @param chargeRoomDetail 实例对象
     * @return 实例对象
     */
    @Override
    public JsonResult update(ChargeRoomDetail chargeRoomDetail) {
        int i = this.chargeRoomDetailMapper.update(chargeRoomDetail);
        return i > 0 ? JsonResult.ok("修改成功！", null) : JsonResult.error("修改失败！");
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public JsonResult deleteById(String id) {
        chargeDetailMapper.deleteByRDId(id);
        return this.chargeRoomDetailMapper.deleteById(id) > 0 ? JsonResult.ok("删除成功！", null) : JsonResult.error("删除失败！");
    }

    @Override
    public JsonResult pageList(RoomDetailForm roomDetailForm) {
        Page<Object> page = PageHelper.startPage(roomDetailForm.getPage(), roomDetailForm.getLimit());
        List<RoomDetailVo> roomDetailVos = chargeRoomDetailMapper.pageList(roomDetailForm);
//        List<RoomDetailVo> roomDetailVos = chargeRoomDetailMapper.pageListcbi(roomDetailForm);
        PageInfo<RoomDetailVo> pageInfo = new PageInfo<>(roomDetailVos);
        pageInfo.setPages(page.getPages());
        pageInfo.setTotal(page.getTotal());
        return JsonResult.ok(pageInfo);
//        Map map = new HashMap<>();
//        map.put("villageId", roomDetailForm.getVillageId());
//
//        if (roomDetailForm.getBuild() != null) {
//            map.put("buildId", roomDetailForm.getBuild());
//        }
//        if (roomDetailForm.getUnit() != null) {
//            map.put("unitId", roomDetailForm.getUnit());
//        }
//        if (roomDetailForm.getRoom() != null) {
//            map.put("roomId", roomDetailForm.getRoom());
//        }
//
//        List<SysHouse> allHouse = modularSupport.getAllHouse(map);
//        List<RoomDetailVo> resultList = new ArrayList<>();
//        Map<String, List<RoomDetailVo>> resultMap = new HashMap<>();//存放重新组装过后的数据集合
//
//        for (int i = 0; i < allHouse.size(); i++) {
//            ChargeRoomDetail roomDetail = new ChargeRoomDetail();
//            SysHouse sysHouse = allHouse.get(i);
//            roomDetail.setRoomId(sysHouse.getRoomId());
//
//            List<ChargeRoomDetail> chargeRoomDetails = chargeRoomDetailMapper.queryAll(roomDetail);
//            for (ChargeRoomDetail s: chargeRoomDetails) {
//                RoomDetailVo roomDetailVo = addRoomDetail(s, roomDetailForm.getVillageId()); //通过roomId userId获取数据，重新组装
//
//                if (resultMap.containsKey(roomDetail.getRoomId())) {
////                resultMap.get(roomDetail.getRoomId()).add(roomDetailVo);
//                } else {
//                    resultList.add(roomDetailVo);
//                    resultMap.put(roomDetail.getRoomId(), resultList);
//                }
//            }
//
//        }
//
//        List<RoomDetailVo> dataList = new ArrayList<>();
//        for (int i = (roomDetailForm.getPage() - 1) * roomDetailForm.getLimit(); i < roomDetailForm.getPage() * roomDetailForm.getLimit(); i++) {
//            if (resultList.size() == i) {
//                break;
//            }
//            dataList.add(resultList.get(i));
//        }
//
//        PageBo pageBo = new PageBo<List<RoomDetailVo>>();
//        pageBo.setTotal(resultList.size());
//        pageBo.setPage(roomDetailForm.getPage());
//        pageBo.setLimit(roomDetailForm.getLimit());
//        pageBo.setData(dataList);
//
//
//
//        return JsonResult.ok(pageBo);
    }

    @Override
    public JsonResult getOneRoom(RoomDetailForm roomDetailForm) {
        ChargeRoomDetail chargeRoomDetail = new ChargeRoomDetail();
        if (roomDetailForm.getRoom() != null) {
            chargeRoomDetail.setRoomId(roomDetailForm.getRoom());
        }

        List<ChargeRoomDetail> roomDetailList = chargeRoomDetailMapper.queryAll(chargeRoomDetail);
        List<RoomDetailVo> resultList = new ArrayList<>();

        for (int i = 0; i < roomDetailList.size(); i++) {

            ChargeRoomDetail roomDetail = roomDetailList.get(i);
            RoomDetailVo roomDetailVo = addRoomDetail(roomDetail, roomDetailForm.getVillageId()); //通过roomId获取数据，重新组装

            resultList.add(roomDetailVo);

        }


        return JsonResult.ok(resultList);
    }

    public RoomDetailVo addRoomDetail(ChargeRoomDetail roomDetail, String villageId) {
        RoomDetailVo roomDetailVo = new RoomDetailVo();
        RoomUser userByUId = null;
        Map map = new HashMap<>();  //查询条件
        map.put("roomId", roomDetail.getRoomId());
        map.put("villageId", villageId);
//        if (roomDetail.getUserId() != null){
//            map.put("userId",roomDetail.getUserId());
//            userByUId = modularSupport.getRoomUser(map); //得到业主信息
//        }
        SysHouse roomById = modularSupport.getRoomById(map); //得到房间信息
        List<RoomUser> userByRId = modularSupport.getUserByRId(map);

        for (RoomUser r : userByRId) {
            if (r.getUserType().equals("11")) {
                userByUId = r;
                break;
            }
        }

        if (roomDetail.getStandardId() != null) {
            ChargeStandardVO standardVO = chargeStandardMapper.queryOne(roomDetail.getStandardId());
            roomDetailVo.setChargeItem(standardVO.getItemsName());
            roomDetailVo.setMetering(standardVO.getStandardMetering());
            roomDetailVo.setPrice(standardVO.getStandardPrice());
            roomDetailVo.setMoney(standardVO.getStandardCalculation());
            roomDetailVo.setMetering(standardVO.getStandardMetering());
        }

        if (roomDetail.getId() != null) {
            roomDetailVo.setStartTime(roomDetail.getChargeStime());
            roomDetailVo.setEndTime(roomDetail.getChargeEtime());
            roomDetailVo.setRemark(roomDetail.getRemark());
            roomDetailVo.setId(roomDetail.getId());
            roomDetailVo.setItemsId(roomDetail.getItemsId());
            roomDetailVo.setStandardId(roomDetail.getStandardId());
            roomDetailVo.setMoneys(roomDetail.getMoneys());
        }
        if (userByUId != null) {
            roomDetailVo.setUserName(userByUId.getUserName());
            roomDetailVo.setTel(userByUId.getUserPhone());
            roomDetailVo.setIsCheck(userByUId.getIsCheck());
            roomDetailVo.setUserId(userByUId.getUserId());
        }
        roomDetailVo.setRoomId(roomDetail.getRoomId());
        roomDetailVo.setBuild(roomById.getBuildName());
        roomDetailVo.setRoom(roomById.getRoomName());
        roomDetailVo.setArea(roomById.getRoomArea());
        roomDetailVo.setUnit(roomById.getUnitName());
        roomDetailVo.setStatus(roomById.getStatus());


        return roomDetailVo;
    }

    /**
     * 获取两个时间节点之间的月份列表
     **/
    private static List<String> getMonthBetween(Calendar min, Calendar max) {
        ArrayList<String> result = new ArrayList<String>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//格式化为年月

//        Calendar min = Calendar.getInstance();
//        Calendar max = Calendar.getInstance();
//        min.setTime(minDate);
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

//        max.setTime(maxDate);
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }

        return result;
    }

    public static String getFirstAndLastDayOfMonth(String date_str) {
        String dataTime = "";
        try {
            Calendar cale = Calendar.getInstance();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            cale.setTime(formatter.parse(date_str));

            cale.add(Calendar.MONTH, 0);
            cale.set(Calendar.DAY_OF_MONTH, 1);
            String firstDayOfMonth = formatter.format(cale.getTime()); // 当月第一天 2019-02-01

            cale.add(Calendar.MONTH, 1);
            cale.set(Calendar.DAY_OF_MONTH, 0);
            String lastDayOfMonth = formatter.format(cale.getTime()); // 当月最后一天 2019-02-28

            dataTime = firstDayOfMonth + "~" + lastDayOfMonth;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return dataTime;
    }

//    public static void main(String[] args) {
//        String s = getFirstAndLastDayOfMonth("2020-02");
//        System.out.println(s);
//    }
}